//
//  StatusViewModel.swift
//  CBWWeiBo
//
//  Created by 陈博文 on 16/1/13.
//  Copyright © 2016年 陈博文. All rights reserved.
//

import UIKit

class StatusViewModel: NSObject {
// MARK:=============== 1.成员属性 ===============
    /// 微博格式化之后的来源字符串
    var source_str: String?
    /// 微博格式化之后的创建时间
    var created_str: String?
    /// 用户头像URL
    var icon_image_url: NSURL?
    /// 用户的认证类型对应的图片
    var verified_image: UIImage?
    /// 会员图标
    var mbImage: UIImage?
// MARK:=============== 2.模型(status) ===============
    /// 数据模型
    var status: Status
    
    init(status: Status)
    {
        self.status = status
        
        super.init()
        
        // 1.处理来源
        source_str = self.createSourceStr()
        // 2.处理时间
        created_str = self.createStr()
        // 3.头像
        icon_image_url = self.createIconURL()
        // 4.处理认证类型
        verified_image = self.createVerifiedImage()
        // 5.处理会员图标
        mbImage = self.createMbImage()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
   // MARK:=============== 3.内部处理方法 ===============
    private func createSourceStr() -> String{
        
        if let sourceStr: NSString = status.source where sourceStr != ""
        {
            // 1.获取从什么地方开始截取
            let location = sourceStr.rangeOfString(">").location + 1
            // 2.获取截取字符串的长度
            // 注意:rangeOfString默认是从前外后查找, 只要找到一个就不会继续查找
            let length = sourceStr.rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - location
            // 3.截取字符串
            let temp = sourceStr.substringWithRange(NSMakeRange(location, length))
            return "来自: " + temp
        }
        return "来自: 小码哥"
    }
    
    
    private func createStr() -> String?{
        let createDate = NSDate.dateFromStr(status.created_at ?? "")
        return createDate?.descString()
    }
    
    
    private func createIconURL() -> NSURL?{
        //        XMGLog("处理数据")
        return  NSURL(string: status.user?.profile_image_url ?? "")
    }
    
    
    private func createVerifiedImage() ->UIImage?{
        //  0，认证用户，2,3,5: 企业认证，220: 达人
        switch status.user?.verified_type ?? -1
        {
        case 0:
            return UIImage(named: "avatar_vip")
        case 2, 3, 5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return nil
        }
        
    }
    
    
    private func createMbImage() -> UIImage?{
        let rank = status.user?.mbrank ?? 0
        if rank >= 1 && rank <= 6
        {
            return UIImage(named: "common_icon_membership_level\(rank)")
        }
        return nil
    }

    
    
}
